package com.example.multidatasource.config;

import com.alibaba.druid.pool.DruidDataSource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

@Slf4j
@Component
public class DataSourceConfig {

    @Autowired
    private DruidDataSourceProperties druidDataSourceProperties;

    @Autowired
    private MultiDataSource multiDataSource;

    @Bean
    @ConditionalOnProperty(name = "spring.enable.multi.datasource",havingValue = "false")
    public DruidDataSource singleDataSource(){
        log.info("singleDataSource");
        return druidDataSourceProperties.config(new DruidDataSource());
    }

    @Bean
    @ConditionalOnProperty(name = "spring.enable.multi.datasource",havingValue = "true")
    public DynamicDataSource multiDataSources(){
        log.info("multiDataSource");
        Map<Object,Object> dbSource = new HashMap<>();
        //主数据源
        DruidDataSource druidDataSource = druidDataSourceProperties.config(new DruidDataSource());
        dbSource.put("primary",druidDataSource);
        //其他数据源
        if (multiDataSource != null){
            List<DruidDataSource> dataSources = multiDataSource.getDatasource().stream()
                    .filter(db -> !"".equals(Optional.ofNullable(db.getDbName()).orElse("")))
                    .map(db -> {
                        DruidDataSource druidDS = db.config(druidDataSourceProperties.config());
                        dbSource.put(db.getDbName(), druidDS);
                        return druidDS;
                    }).collect(Collectors.toList());
            try {
                //多数据源需要手动初始化
                druidDataSource.init();
                for (DruidDataSource dataSource : dataSources) {
                    dataSource.init();
                }
            } catch (SQLException e) {
                e.printStackTrace();
                log.error(e.getMessage(),e);
            }
        }
        DynamicDataSource dynamicDataSource = new DynamicDataSource();
        dynamicDataSource.setTargetDataSources(dbSource);
        dynamicDataSource.setDefaultTargetDataSource(druidDataSource);
        return dynamicDataSource;
    }

}
